package com.linkoog.devtools.icon_viewer.converters;

import com.linkoog.devtools.icon_viewer.ImageToIconConverter;
import com.linkoog.devtools.icon_viewer.core.Base64;
import com.linkoog.devtools.icon_viewer.core.IconType;
import com.linkoog.devtools.icon_viewer.core.ImageWrapper;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.ui.scale.DerivedScaleType;
import com.intellij.ui.scale.ScaleContext;
import com.intellij.util.IconUtil;
import com.intellij.util.SVGLoader;
import com.intellij.util.ui.ImageUtil;

import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

public class SVGImageConverter implements ImageToIconConverter {

    private static final List<String> extensions = new ArrayList<>(Arrays.asList("svg"));

    @Override
    public Collection<String> getExtensions() {
        return extensions;
    }

    @Override
    public IconType getIconType() {
        return IconType.SVG;
    }

    @Override
    public Image loadImage(ByteArrayInputStream byteArrayInputStream, VirtualFile virtualFile) throws IOException {
        Ref<URL> urlRef = new Ref<>();
        try {
            urlRef.set(new File(virtualFile.getPath()).toURI().toURL());
            URL url = urlRef.get();

            InputStream stream =  virtualFile.getInputStream();
            //FileInputStream stream = new FileInputStream(virtualFile.getPath());
            ScaleContext context = ScaleContext.create();


            BufferedImage image = (BufferedImage)SVGLoader.loadHiDPI(url, stream, context);
            return ImageUtil.ensureHiDPI(image, context);
        } catch (Exception ex) {
            //LOG.warn(ex.message)
        }
        return null;
    }

    @Override
    public Icon convert(VirtualFile canonicalFile, String canonicalPath) throws IOException {
        if (canonicalFile == null) return null;

        ImageWrapper imageWrapper = getImageWrapper(canonicalFile);
        if (imageWrapper == null) return null;

        ImageWrapper fromBase64 = fromBase64(toBase64(imageWrapper), getIconType(), canonicalFile) ;
        if (fromBase64 == null) return null;

        return IconUtil.createImageIcon(fromBase64.getImage());
    }

    @Override
    public String toBase64(ImageWrapper imageWrapper) {
        return Base64.encode(imageWrapper.getFileContents());
    }
}
